<?php
namespace App\HttpController;



use EasySwoole\Queue\Job;
use EasySwoole\Http\AbstractInterface\Controller;
use App\Models\AdminModel;
use App\Models\UserModel;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Component\Di;
use App\HttpController\UserBase;
use App\Models\Project;
use App\service\MyQueue;
use App\Models\Assign;
use App\Models\History;
use App\Models\FileApp;
class Leader  extends UserBase
{

    function list(){
        $limit = \EasySwoole\EasySwoole\Config::getInstance()->getConf('pagelimit');
        $model = Project::create();
        $page = $this->input('page',1);
        $owner = $this->input("owner","");
        $lxnumber = $this->input("lxnumber","");
        $name = $this->input("name","");
        $wtdw = $this->input("wtdw","");
        $bzjg = $this->input("bzjg","");
        $addtime = $this->input("addtime","");
        $industry = $this->input("industry","");
        $wtdwcontactor = $this->input("wtdwlxr","");
        $pslb = $this->input("pslb","");
        $where = [];
        if($owner == 'null'){
            $owner = "";
        }
    
        if($industry == 'null' || $industry == "1"){
            $industry = "";
        }
    
        if($lxnumber == 'null'){
            $lxnumber = "";
        }
        if($name == 'null'){
            $name = "";
        }
        if($wtdw == 'null'){
            $wtdw = "";
        }
        if($bzjg == 'null'){
            $bzjg = "";
        }
        if($pslb == 'null'){
            $pslb = "";
        }
        if($wtdwcontactor == 'null'){
            $wtdwcontactor = "";
        }
       
    
        if($owner){
            $model = $model->where("owner","%".$owner."%",'like');
        }
    
        if($lxnumber){
       
            $model = $model->where("lxnumber","%".$lxnumber."%",'like');
        }
        if($name){
            $model = $model->where("name","%".$name."%",'like');
        }
        if($wtdw){
            $model = $model->where("wtdw","%".$wtdw."%",'like');
        }
        if($bzjg){
            $model = $model->where("bzjg","%".$bzjg."%",'like');
        }
        
        if($industry){
            $model = $model->where(["industry"=>$industry]);
        }
    
        if($pslb && $pslb!='1'){
            $model = $model->where(['approve_type'=>$pslb]);
        }
        if($wtdwcontactor){
            $model = $model->where("wtdwcontactor","%".$wtdwcontactor."%",'like');
        }

          $st = $this->input("st");
          if($st=="done"){
            $list = $model->where('status',3,'>=');
          }else{
            $list = $model->where(['status'=>1]);
          }
    

          $model = $model->order('id', 'DESC')->limit($limit * ($page - 1), $limit)->withTotalCount();
          $list = $model->all(null);
          $result = $model->lastQueryResult();
          $total = $result->getTotalCount();
          $pagecon = $this->showPageStringAsAJAXForitem("jumpage",$page,$limit,$total,$owner);
          $this->writeJson(200,['list'=>$list,'pg'=>$pagecon]);
    }


    function reject(){

        $id = intval($this->input("id"));
        $reason = $this->input("reason");

        $data = ['userid'=>$this->who['id'],'approveres'=>0,
    'idea'=>$reason,'isgroup'=>0,'usertype'=>$this->who['type'],'itemid'=>$id,
  "addtime"=>time()];


  try {
    // 开启事务
    \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
    
    $item = Project::create()->get(['id'=>$id]);
    Assign::create()->update(['status'=>2],['itemid'=>$id]);
        
    $this->logapprove($data['userid'],0,$id,$reason,0,$data['usertype']);

    $res = Project::create()->update(['status'=>-1,'approveuuid'=>NULL],['id'=>intval($id)]);


    // 提交事务
    \EasySwoole\ORM\DbManager::getInstance()->commit();
    $this->writeJson(200,['code'=>200]);
} catch(\Throwable  $e){
    // 回滚事务
    \EasySwoole\ORM\DbManager::getInstance()->rollback();
}


    }


  function getassign(){

    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $assigns = Assign::create()->where('status',[0,1],'in')->all(['itemid'=>$id]);

    if($assigns){
        $this->writeJson(200,['code'=>505,'msg'=>'系统检测目前此项目已分配了专家，请先取消，再选择']);

    }else{

        $this->WriteJson(200,['code'=>200]);
    }
}




   function detail(){
    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $item  =Project::create()->get(['id'=>$id]);
    $assigns_leader = Assign::create()->all(['issystem'=>0,'itemid'=>$id]);


    $system_assigns = Assign::create()->join("user_list","user_list.id=assign.assign_eid")->field(["assign.*",
    "user_list.phone","user_list.good"])->all(['assign.itemid'=>$id,'assign.issystem'=>1,'assign.status'=>[[1,0],'in']]);


    $allassigneids =  Assign::create()->where(['itemid'=>$id,'status'=>[[1,0],'in']])->column("assign_eid");

    $item['assign'] = [
        'system'=>$system_assigns,
        "leader"=>$assigns_leader
    ];

    $systtemid = array_column($system_assigns,"assign_eid");


    $systtemusers = Assign::create()->where(['assign.itemid'=>$id,'assign.issystem'=>1,'assign.status'=>[[1,0],'in']])->column("assign_eid");


    if(!$systtemusers){
        $systtemusers = [0];
    }

    $expert_jg = UserModel::create()->where("id",$systtemusers,"not in")->all(['type'=>5,'approve_level'=>$item['type']]);

    for($i=0;$i<count($expert_jg);$i++){
        $expert_jg[$i]['ischoosed'] = in_array($expert_jg[$i]['id'],$allassigneids);
    }


    $expert_person = UserModel::create()->where("id",$systtemusers,"not in")->all(['type'=>4,'approve_level'=>$item['type']]);
    for($i=0;$i<count($expert_person);$i++){

        $expert_person[$i]['ischoosed'] = in_array($expert_person[$i]['id'],$allassigneids);
        
        if(in_array($expert_person[$i]['id'],$allassigneids)){
            $expert_person[$i]['isgroup'] = Assign::create()->get(['itemid'=>intval($id),
        'isgroupleader'=>1,'assign_eid'=>$expert_person[$i]['id']]) ? true :false;
        }else{

            $expert_person[$i]['isgroup'] =false;

        }

    }


    $item['allexps'] = [
        "exp"=>$expert_person,'exjg'=>$expert_jg
    ];

    if ($item['cash'] < Config::getInstance()->getConf('CASH_TRIGGER')) {
        $item['isjg'] = true;
    }else{
        $item['isjg'] = false;
    }
    $this->writeJson(200,$item);
   }




   function dsdetail(){
    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $log = History::create()->join('user_list','user_list.id = approve_history.userid')->field(["approve_history.*","user_list.displayname"])->all(['itemid'=>$id]);
    var_dump($log);
    for($i=0;$i<count($log);$i++){
        $log[$i]['file'] = \App\Models\FileApp::create()->all(['approveid'=>$log[$i]['id']]);
    
    }
    $item  =Project::create()->get(['id'=>$id]);
    for($i=0;$i<count($log);$i++){
        $log[$i]['info'] = UserModel::create()->get(['id'=>$log[$i]['userid']]);
    }
    $this->writeJson(200,['item'=>$item,'logs'=>$log]);
   }


   function confirm(){

    $para= $this->request()->getRequestParam();
    $itemid = $para['itemid'];


    $assign = Assign::create()->all(['status'=>0,'itemid'=>intval($itemid)]);

    if(!$assign){
        $this->writeJson(200,['code'=>500,'msg'=>'没有选定机构，请先选择一个机构']);
        return false;
    }

    try {
        // 开启事务
        \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
        $uuid = md5(time());
        // 执行更新 $model 的更新操作
        Assign::create()->update(['status'=>1,'uuid'=>$uuid],['status'=>0,'itemid'=>intval($itemid)]);

        Project::create()->update(['status'=>3,'approveuuid'=>$uuid],['id'=>$itemid]);
    
        // 提交事务
        \EasySwoole\ORM\DbManager::getInstance()->commit();
        $this->writeJson(200,['code'=>200]);
    } catch(\Throwable  $e){
        // 回滚事务
        \EasySwoole\ORM\DbManager::getInstance()->rollback();
    }

   }



   function dealitem(){
    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $item  =Project::create()->get(['id'=>$id]);
    if ($item['status'] != 6) {
        $this->writeJson(200,['code'=>500],'this project has a error status');
        return false;
    }
    try {
        // 开启事务
      $isopen  =   \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
        if($data['appres'] == 1){
            $status = 7;
        }else{
            $status = -1;
        }
        // 执行更新 $model 的更新操作
        $logid = $this->logapprove($this->who['id'],$data['appres'],$id,$data['idea'],0,$this->who['type']);

        $file2 = $this->input("files");
      
        if($file2){
            $datafiles = [];
        foreach($file2 as $k=>$v){
            array_push($datafiles,[
                "name"=>$v['filename'],
                "path"=>$v['filepath'],
                "approveid"=>$logid,
                "userid"=>$this->who['id'],
                "time"=>time(),
            ]);
        }
   
        FileApp::create()->saveall($datafiles,true,false);
    }

        Project::create()->update(['status'=>$status],['id'=>$id]);
        // 提交事务
        \EasySwoole\ORM\DbManager::getInstance()->commit();

        $this->writeJson(200,['code'=>200],"ok");
    } catch(\Throwable  $e){
        // 回滚事务
        \EasySwoole\ORM\DbManager::getInstance()->rollback();
        var_dump($e->getMessage());
        $this->writeJson(200,['code'=>500],"error db");
    }
   }




   //choose an expert  orga
function selectExpt(){
    $userid = $this->input("userid");
    $itemid = $this->input("itemid");
    $assigns = Assign::create()->all(['itemid'=>intval($id)]);
    $item = Project::create()->get(['id'=>intval($itemid)]);
    if($assigns){
        $this->writeJson(200,['code'=>505,'msg'=>'系统检测目前此项目已分配了专家，请先取消，再选择']);

    }else{

        $cash_trigger = Config::getInstance()->getConf('CASH_TRIGGER');

        if($item['cash'] < $cash_trigger){
                $selectjg = UserModel::create()->get(['id'=>intval($userid)]);
                if($selectjg){
                    $data = ['assign_eid'=>$selectjg['id'],'issystem'=>0,'assgin_displayname'=>$selectjg['displayname'],'addtime'=>time(),'status'=>0,'itemid'=>$item['id']];
                    Assign::create($data)->save();
                    $this->writeJson(200,['code'=>200,'msg'=>'已选定该机构']);
                }

        }else{
            //...
            echo "found nb";
            $this->writeJson(200,['code'=>505,'msg'=>'系统发现非法操作，拒绝了你的请求']);

        }



   }
}







function cancelExpt(){


    $userid = $this->input("userid");
    $itemid = $this->input("itemid");
   

    $res = Assign::create()->destroy(['assign_eid' => intval($userid),'itemid'=>intval($itemid)]);

    if($res){


        $this->writeJson(200,['code'=>200,'msg'=>'取消机构成功']);
    }
}




function cancelZJ(){


    $id = $this->input("id");
    $itemid = $this->input("itemid");
   

    $res = Assign::create()->destroy(['assign_eid' => intval($id),'itemid'=>intval($itemid),'status'=>0]);

    if($res){
        $this->writeJson(200,['code'=>200,'msg'=>'取消机构成功']);
    }
}


function setgroup(){
    $userid = $this->input("userid");
    $itemid = $this->input("itemid");
   

    $isexist = Assign::create()->get(['status'=>0,'itemid'=>intval($itemid),'assign_eid'=>intval($userid)]);

    if(!$isexist){
        $this->writeJson(200,['code'=>540,'msg'=>'你必须先将用户选定，才能将设置为组长']);
        return false;
    }

    $isexistgroup = Assign::create()->get(['status'=>0,'itemid'=>intval($itemid),'isgroupleader'=>1]);
    if($isexistgroup){
        $this->writeJson(200,['code'=>540,'msg'=>'已经存在组长，请先取消组长，再选择新的组长']);
        return false;
    }

    $res = Assign::create()->update(['isgroupleader'=>1],['id'=>$isexist['id']]);

    if($res){
        $this->writeJson(200,['code'=>200,'msg'=>'设置组长成功']);
    }
}






   //choose an expert  orga
   function selectZJ(){
    $userid = $this->input("userid");
    $itemid = $this->input("itemid");
    $item = Project::create()->get(['id'=>intval($itemid)]);
    $cash_trigger = Config::getInstance()->getConf('CASH_TRIGGER');

        if($item['cash'] >= $cash_trigger){
                $selectp = UserModel::create()->get(['id'=>intval($userid)]);
                if($selectp){
                    $data = ['assign_eid'=>$selectp['id'],'issystem'=>0,'assgin_displayname'=>$selectp['displayname'],'addtime'=>time(),'status'=>0,'itemid'=>$item['id']];
                    Assign::create($data)->save();
                    $this->writeJson(200,['code'=>200,'msg'=>'已选定该机构']);
                }
        }else{

            $this->writeJson(200,['code'=>500,'msg'=>'该项目只能选择个人专家']);
        }
    }


    function confirmZJ(){

        $itemid = $this->input("itemid");
        $item = Project::create()->get(['id'=>intval($itemid)]);
        $cash_trigger = Config::getInstance()->getConf('CASH_TRIGGER');

        $group = Assign::create()->where(['isgroupleader'=>1,'itemid'=>intval($itemid),'status'=>0])->get();

        if(!$group){

            $this->writeJson(200,['code'=>500,'msg'=>'该项目必须指定一名组长']);
            return false;
        }


        try {
            // 开启事务
            \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
            $uuid = md5(time());

            Assign::create()->update(['status'=>1,'uuid'=>$uuid],['status'=>0,'itemid'=>intval($itemid)]);
           
           
           
            Project::create()->update(['status'=>3,'approveuuid'=>$uuid],['id'=>$itemid]);
    
            // 提交事务
            \EasySwoole\ORM\DbManager::getInstance()->commit();
    
            $this->writeJson(200,['code'=>200],"ok");
        } catch(\Throwable  $e){
            // 回滚事务
            \EasySwoole\ORM\DbManager::getInstance()->rollback();
            var_dump($e->getMessage());
            $this->writeJson(200,['code'=>500,'mag'=>'异常发生，请联系管理员'],"error db");
        }
    }







function celgroup(){
    $userid = $this->input("userid");
    $itemid = $this->input("itemid");
   

    $isexist = Assign::create()->get(['status'=>0,'itemid'=>intval($itemid),'assign_eid'=>intval($userid),'isgroupleader'=>1]);

    if(!$isexist){
        $this->writeJson(200,['code'=>540,'msg'=>' 此用户不是组长']);
        return false;
    }

    $res = Assign::create()->update(['isgroupleader'=>0],['id'=>$isexist['id']]);

    if($res){
        $this->writeJson(200,['code'=>200,'msg'=>'取消组长成功']);
    }
}



}